<template>
    <div>
        <van-search v-model="value" show-action :placeholder="defaultKeyword" @search="onSearch" @cancel="onCancel"
            @update:model-value="onInput" />
        <RouterView :hotKeywordVOList="hotKeywordVOList" :searchTipsArr="searchTipsArr"
            :searchHistoryData="searchHistoryData" :deleteHistory="deleteHistory" :valuechange="valuechange"></RouterView>
    </div>
</template>

<script lang="ts">
import { defineComponent } from "vue"
import { useRouter } from 'vue-router';
export default defineComponent({
    name: 'search',
})
</script>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { reqGetKeyWord, reqSearchAuto } from '@/api/search'





const value = ref("")
const defaultKeyword = ref("") //默认关键字
const searchHistoryData = ref<string[]>(JSON.parse(localStorage.getItem("searchHistoryData") as string) || []) //历史记录
const hotKeywordVOList = ref([])//搜索热门关键字
const searchTipsArr = ref<string[]>([])//自动的搜索的结果

onMounted(async () => {
    const res = await reqGetKeyWord()
    console.log(res);
    defaultKeyword.value = res.defaultKeyword.keyword;
    // searchHistoryData.value = res.data.searchHistoryData;
    hotKeywordVOList.value = res.hotKeywordVOList;

});
const router = useRouter()
const onSearch = (keyword: any) => {
    let rest = JSON.parse(localStorage.getItem("searchHistoryData") as string)
    if (rest === null) {
        rest = [keyword]
    } else {
        const last = rest.indexOf(keyword)
        if (last !== -1) {
            rest.splice(last, 1)
        }
        rest.unshift(keyword)
    }
    localStorage.setItem("searchHistoryData", JSON.stringify(rest))
    searchHistoryData.value = JSON.parse(localStorage.getItem("searchHistoryData") as string)
    value.value = keyword
    router.push({
        path: "/search/classIficationlist",
        query: {
            keyword
        }
    })

};
const onCancel = () => {
    // console.log("取消");
    window.history.go(-1);
};

const onInput = async (value: string) => {
    const params = {
        token: localStorage.getItem("token"),
        keywordPrefix: value
    }
    try {
        const res = await reqSearchAuto(params)
        console.log(res);
        //保存数据
        searchTipsArr.value = res
    } catch (error) {

    }
};
const deleteHistory = () => {
    localStorage.setItem("searchHistoryData", JSON.stringify([]))
    searchHistoryData.value = []
}
const valuechange = (val: string) => {
    value.value = val
}










</script>

<style lang="scss" scoped></style>